import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// 只允许输入小数
class UsNumberTextInputFormatter extends TextInputFormatter {
  num? maxSum; //最大值，默认为十亿
  static const int maxLength = 1000000000;
  UsNumberTextInputFormatter({this.maxSum});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    debugPrint("====进入了,${oldValue.text},${newValue.text}");
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    double newSum = 0.0;
    try {
      newSum = double.parse(value);
    } catch (e) {
      debugPrint("flutter double转换异常,$value");
    }
    debugPrint("flutter double转换成功,$newSum，最大${maxSum ?? maxLength}");
    if (newSum > (maxSum ?? maxLength)) {
      //限制最大值
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    } else {
      if (value == '.') {
        value = '0.';
        selectionIndex++;
      } else if (value.contains(".")) {
        var data = value.split(".");
        if ((data.length == 2 && data[1].length > 2) || data.length > 2) {
          value = oldValue.text;
          selectionIndex = oldValue.selection.end;
        }
      }
    }
    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
